import os
import shutil
import sys

import requests
import zipfile

class deploy_project:
    url = ""
    dir = ""
    def __init__(self, dir,url):
        self.url = url
        self.dir = dir

# 下载文件
def download_file(url, save_path):
    response = requests.get(url)
    with open(save_path, 'wb') as file:
        file.write(response.content)
    print(f"文件已下载到 {save_path}")

# 解压文件
def unzip_file(zip_path, extract_to):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        for zip_info in zip_ref.infolist():
            try:
                # 尝试先解码为 UTF-8（常见于现代 ZIP 文件）
                filename = zip_info.filename.encode('cp437').decode('utf-8')
            except (UnicodeEncodeError, UnicodeDecodeError):
                try:
                    # 回退到 GBK（兼容中文 Windows 生成的 ZIP）
                    filename = zip_info.filename.encode('cp437').decode('gbk')
                except:
                    # 终极回退：直接使用原始文件名
                    filename = zip_info.filename
            # 处理路径分隔符和非法字符
            filename = filename.replace('\\', '/')  # 统一路径格式
            filename = os.path.normpath(filename)   # 规范化路径
            
            # 确保目标目录存在
            target_path = os.path.join(extract_to, filename)
            os.makedirs(os.path.dirname(target_path), exist_ok=True)
            
            # 解压文件（跳过目录）
            if not filename.endswith('/'):
                zip_ref.extract(zip_info, extract_to)
    print(f"文件已解压到 {extract_to}")

# 删除
def delete_file(zip_path):
    if os.path.isdir(zip_path):  # 判断是否是目录
        shutil.rmtree(zip_path)  # 删除目录
        print(f"已删除目录 {zip_path}")
    elif os.path.isfile(zip_path):  # 判断是否是文件
        os.remove(zip_path)  # 删除文件
        print(f"已删除文件 {zip_path}")
    else:
        print("文件或目录不存在，无法删除")


# 重命名文件夹
def rename_folder(old_path, new_name):
    parent_dir = os.path.dirname(old_path)
    new_path = os.path.join(parent_dir, new_name)
    if(new_path != old_path):
        shutil.move(old_path,new_path)
        print(f"访问路由重命名为 {new_name}")

# 备份压缩包
def backup_zip(zip_file_path):
    backup_path = os.path.join(os.path.dirname(zip_file_path),r'backup')
    if not os.path.exists(backup_path):
        os.mkdir(backup_path)
    shutil.move(zip_file_path,os.path.join(backup_path,os.path.basename(zip_file_path)))


def auto_deploy():
    for t_deploy_project in auto_deploy_project:
        try:
            url = t_deploy_project.url
            dir = t_deploy_project.dir
            url_list = url.split("/")
            zip_name = url_list[len(url_list)-1].replace(".zip","")
            zip_file_path = os.path.join(root_directory, zip_name+".zip")
            extract_directory = root_directory    #解压文件存放的文件夹
            exists_directory = os.path.join(root_directory, dir)     #项目正在使用的文件夹

            # 删除正在使用的文件
            if os.path.exists(exists_directory):
                delete_file(exists_directory)
            # 下载文件到指定目录
            download_file(url, zip_file_path)
            # 解压文件
            unzip_file(zip_file_path, extract_directory)
            # 重命名项目名
            rename_folder(os.path.join(root_directory,zip_name), dir)

            # 备份压缩包
            backup_zip(zip_file_path)

        except Exception as e:
            print('当前项目部署异常跳过本次部署',e)

################################################################################################
# 根目录
root_directory = r"D:\localservice\html\mcpc\ui"

# 项目部署路由及升级包下载路径
auto_deploy_project = [
    deploy_project('dist','http://192.168.10.205:8080/view/%E4%BA%94%E5%A4%A7%E4%B8%AD%E5%BF%83/job/WDZX_PCC/ws/dist/*zip*/dist.zip'),
    deploy_project('h5','http://192.168.10.205:8080/view/%E4%BA%94%E5%A4%A7%E4%B8%AD%E5%BF%83/job/WDZX_prehospitalH5/ws/unpackage/dist/build/prehospitalH5/*zip*/prehospitalH5.zip'),
    deploy_project('jjh5','http://192.168.10.205:8080/view/%E4%BA%94%E5%A4%A7%E4%B8%AD%E5%BF%83/job/WDZX_greenPathH5/ws/unpackage/dist/build/greenPathH5/*zip*/greenPathH5.zip'),
    # deploy_project('WEB-INF','http://192.168.10.205:8080/view/%E4%BA%94%E5%A4%A7%E4%B8%AD%E5%BF%83/job/%E4%BA%94%E5%A4%A7%E4%B8%AD%E5%BF%83-%E5%90%8E%E7%AB%AF-medex_mdap_mcpc/ws/medex_mdap_mcpc/target/mcpc/WEB-INF/*zip*/WEB-INF.zip')
]
# 接收传入的参数
arguments = sys.argv
script_name = arguments[0]
other_arguments = arguments[1:]

if __name__ == "__main__":
    result = []
    for arg in other_arguments:
        for dp in auto_deploy_project:
            if arg == dp.dir :
                result.append(dp)
    if len(result)>0 : auto_deploy_project = result
    # print(auto_deploy_project)
    auto_deploy()
    #unzip_file(r'D:\localservice\html\mcpc\ui\dist.zip',r'D:\localservice\html\mcpc\ui')